define([], function() {
  var self = {};

  function request(type, api, query, func, err) {
    err = (typeof err == "undefined")
      ? function() {}
      : err;
      // T.B.D. test token
      token = "e298e2d3-994f-4d7a-a25e-e4e136afd630";
    // var token = self.getCookieSessionId();
    $$.ajax({
      method: type,
      cache: false,
      dataType: "json",
      data: query,
      url: '<%= app.config[:api_root] %>' + api,
      headers: {
        Authorization: "Bearer " + token
      },
      success: function(data, status, xhr) {
        func(data, status, xhr);
      },
      error: function(xhr, status) {
        if (xhr.status === 204) {
          func({}, xhr.status, xhr);
        } else if (xhr.status === 401) {
          alert(constants.common.tips_login, function() {
            mainView.router.load({url: 'login.html'})
          });
        } else if (xhr.status !== 200 && xhr.status !== 404) {
          var responseText = JSON.parse(xhr.responseText);
          var errorText;
          $.each(responseText, function(i, val) {
            var field = (typeof constants.fieldText[i] != undefined)
              ? constants.fieldText[i]
              : "";
            errorText = field + val[0];
            return false;
          });
          console.log(xhr);
          alert(errorText);
          err(xhr, status);
        } else {
          err(xhr, status);
        }
      }
    });
  }

  self.get = function(api, query, func, err) {
    request('GET', api, query, func, err);
  }

  return self;
})
